{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9a71fa36",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "# Writing a software application using function calls\n",
    "\n",
    "The default way of creating code in Autogen is its built-in code extractor. Although it allows for creating and executing simple scripts fast, that way of creating code is not suitable for developing advanced software applications, according to my experiences. The process of developing an application is mostly the process of introducing changes into existing files rather than creating new files with code. And in my experience, the code extractor is bad at introducing changes as the model often gets lost and can damage existing files.\n",
    "\n",
    "Properly created functions that can modify code provide us with the ability to have more control over code changes and result in better quality. Additionally, as the scope of possible operations is predefined inside the tools, we can safely use Autogen without Docker, avoiding all the complications related to it.\n",
    "\n",
    "## Requirements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c528cd6d",
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install pyautogen"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5ebd2397",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Set your API Endpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dca301a4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import autogen\n",
    "\n",
    "config_list = [{\"model\": \"gpt-4-turbo-preview\", \"api_key\": os.getenv(\"OPENAI_API_KEY\")}]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "2b9526e7",
   "metadata": {},
   "source": [
    "## Create agents\n",
    "\n",
    "In this example, we will improve a simple FastAPI application using only dedicated function calls. Let's create an Engineer agent that will think out and execute code changes, and a user proxy Admin agent, through which we will guide our Engineer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1a10c9fe-1fbc-40c6-b655-5d2256864ce8",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_config = {\n",
    "    \"temperature\": 0,\n",
    "    \"config_list\": config_list,\n",
    "}\n",
    "\n",
    "engineer = autogen.AssistantAgent(\n",
    "    name=\"Engineer\",\n",
    "    llm_config=llm_config,\n",
    "    system_message=\"\"\"\n",
    "    I'm Engineer. I'm expert in python programming. I'm executing code tasks required by Admin.\n",
    "    \"\"\",\n",
    ")\n",
    "\n",
    "user_proxy = autogen.UserProxyAgent(\n",
    "    name=\"Admin\",\n",
    "    human_input_mode=\"ALWAYS\",\n",
    "    code_execution_config=False,\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "966c96a4-cc8a-4400-b8db-a21b7142e33c",
   "metadata": {},
   "source": [
    "Mention, unlike in many other examples, here we don't need a separate Executor agent to save our code, as that will be done by functions. We also don't need Docker to be running because of that - which makes the entire process easier.\n",
    "\n",
    "Next, let's set up our group chat."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "354b4a8f-7a96-455b-9f17-cbc19d880462",
   "metadata": {},
   "outputs": [],
   "source": [
    "groupchat = autogen.GroupChat(\n",
    "    agents=[engineer, user_proxy],\n",
    "    messages=[],\n",
    "    max_round=500,\n",
    "    speaker_selection_method=\"round_robin\",\n",
    "    enable_clear_history=True,\n",
    ")\n",
    "manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d7b0ad4c-a287-456d-9c0e-c4895e5f8ed2",
   "metadata": {},
   "source": [
    "## Prepare appropriate functions\n",
    "\n",
    "Let's go to core of the thing. Prepare functions that provide Engineer with functionality to modify existing code, create new code files, check filesystem and files.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94b85d81-bdc5-4c9c-a9da-59a796317731",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing_extensions import Annotated\n",
    "\n",
    "default_path = \"backend_dir/\"\n",
    "\n",
    "\n",
    "@user_proxy.register_for_execution()\n",
    "@engineer.register_for_llm(description=\"List files in choosen directory.\")\n",
    "def list_dir(directory: Annotated[str, \"Directory to check.\"]):\n",
    "    files = os.listdir(default_path + directory)\n",
    "    return 0, files\n",
    "\n",
    "\n",
    "@user_proxy.register_for_execution()\n",
    "@engineer.register_for_llm(description=\"Check the contents of a chosen file.\")\n",
    "def see_file(filename: Annotated[str, \"Name and path of file to check.\"]):\n",
    "    with open(default_path + filename, \"r\") as file:\n",
    "        lines = file.readlines()\n",
    "    formatted_lines = [f\"{i+1}:{line}\" for i, line in enumerate(lines)]\n",
    "    file_contents = \"\".join(formatted_lines)\n",
    "\n",
    "    return 0, file_contents\n",
    "\n",
    "\n",
    "@user_proxy.register_for_execution()\n",
    "@engineer.register_for_llm(description=\"Replace old piece of code with new one. Proper indentation is important.\")\n",
    "def modify_code(\n",
    "    filename: Annotated[str, \"Name and path of file to change.\"],\n",
    "    start_line: Annotated[int, \"Start line number to replace with new code.\"],\n",
    "    end_line: Annotated[int, \"End line number to replace with new code.\"],\n",
    "    new_code: Annotated[str, \"New piece of code to replace old code with. Remember about providing indents.\"],\n",
    "):\n",
    "    with open(default_path + filename, \"r+\") as file:\n",
    "        file_contents = file.readlines()\n",
    "        file_contents[start_line - 1 : end_line] = [new_code + \"\\n\"]\n",
    "        file.seek(0)\n",
    "        file.truncate()\n",
    "        file.write(\"\".join(file_contents))\n",
    "    return 0, \"Code modified\"\n",
    "\n",
    "\n",
    "@user_proxy.register_for_execution()\n",
    "@engineer.register_for_llm(description=\"Create a new file with code.\")\n",
    "def create_file_with_code(\n",
    "    filename: Annotated[str, \"Name and path of file to create.\"], code: Annotated[str, \"Code to write in the file.\"]\n",
    "):\n",
    "    with open(default_path + filename, \"w\") as file:\n",
    "        file.write(code)\n",
    "    return 0, \"File created successfully\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a3a09c9",
   "metadata": {},
   "source": [
    "## Prepare code to work with\n",
    "\n",
    "In this example, we will show how AI can extend the functionalities of existing code, as improving existing code is a much more frequent use case in software development than creating a new one. Let's prepare the initial code on which we will work. That will be a simple FastAPI script that will allow you to calculate today's stock spread in percentage for CD Project Red, a famous Polish gamedev company. Create a folder called 'backend_dir' and place a 'main.py' file here with the following content:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "370a9f8d-d5ce-4127-8646-cf0e4effd9f5",
   "metadata": {},
   "source": [
    "```python\n",
    "# backend_dir/main.py\n",
    "\n",
    "from fastapi import FastAPI\n",
    "import yfinance as yf\n",
    "\n",
    "app = FastAPI()\n",
    "\n",
    "@app.get(\"/cdr_daily_spread\")\n",
    "async def calculate_daily_spread():\n",
    "    cdr = yf.Ticker(\"CDR.WA\")\n",
    "    today_data = cdr.history(period=\"1d\")\n",
    "    spread = ((today_data[\"High\"] - today_data[\"Low\"]) / today_data[\"Low\"]) * 100\n",
    "    return spread\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "945003b5-b764-4ef1-99d9-b9464e39dfed",
   "metadata": {},
   "source": [
    "Install needed libraries. We can run our API using:\n",
    "\n",
    "```bash\n",
    "uvicorn main:app --reload\n",
    "```\n",
    "\n",
    "Send a request to 'localhost:8000/cdr_daily_spread' to check if it works.\n",
    "\n",
    "## Edit code using agents\n",
    "\n",
    "Let's assume we want our agents to extend the functionality of the application. Let's modify the endpoint to check the spread also for 11bits, another gamedev company, and compare it for both stocks. Also, let's separate the internal logic into a different file.\n",
    "\n",
    "Finally, instantiate a chat between the Engineer and the Admin. It will start by exploring the filesystem first, and after that, it will wait for our orders. Then, we will explain the task to the Engineer and ask him to provide a plan of changes first - according to my experience, that greatly increases the quality of LLM responses.\n",
    "\n",
    "After that, introduce changes with the Engineer one after another. Ask him to correct something or improve the functionality if needed. Do not hesitate to interrupt the tool's execution if you feel he is going to do something wrong. If errors occur, provide him with the error log and ask him to check out the file to refresh his knowledge about it before actually introducing changes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d5518947",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\n",
      "You will need to improve app in FastApi. For now, check out all the application files, try to understand it and wait for next instructions.\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_SA61u9yCLhyXfd9NCV9TAIiM): list_dir *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"directory\": \"./\"\n",
      "}\n",
      "\u001b[32m*************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION list_dir...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_SA61u9yCLhyXfd9NCV9TAIiM\" *****\u001b[0m\n",
      "[0, [\"main.py\", \"__pycache__\"]]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_IVJNPI12s4fCzysnWjExZjL2): see_file *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"main.py\"\n",
      "}\n",
      "\u001b[32m*************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION see_file...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_IVJNPI12s4fCzysnWjExZjL2\" *****\u001b[0m\n",
      "[0, \"1:from fastapi import FastAPI\\n2:import yfinance as yf\\n3:\\n4:app = FastAPI()\\n5:\\n6:@app.get(\\\"/cdr_daily_spread\\\")\\n7:async def calculate_daily_spread():\\n8:    cdr = yf.Ticker(\\\"CDR.WA\\\")\\n9:    today_data = cdr.history(period=\\\"1d\\\")\\n10:    spread = ((today_data[\\\"High\\\"] - today_data[\\\"Low\\\"]) / today_data[\\\"Low\\\"]) * 100\\n11:    return spread\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "The application is a FastAPI application with a single endpoint `/cdr_daily_spread`. This endpoint calculates the daily spread of the stock \"CDR.WA\" using the `yfinance` library. The spread is calculated as the percentage difference between the high and low prices of the stock for the day.\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  Let's move spread calculation logic to separate file. Create spread_calculation function with ticker argument in it. in our endpoint, we need to compare daily spread for CD Project Red and 11bits Studio - return difference between them.  Start with providing plan of changes. Don't do any changes yet.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "Let's move spread calculation logic to separate file. Create spread_calculation function with ticker argument in it. in our endpoint, we need to compare daily spread for CD Project Red and 11bits Studio - return difference between them.  Start with providing plan of changes. Don't do any changes yet.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "Sure, here is the plan of changes:\n",
      "\n",
      "1. Create a new Python file named `spread_calculation.py`.\n",
      "2. In this file, define a function named `calculate_daily_spread` that takes a `ticker` as an argument. This function will contain the logic to calculate the daily spread of a given stock.\n",
      "3. Modify the `main.py` file to import the `calculate_daily_spread` function from `spread_calculation.py`.\n",
      "4. Modify the `/cdr_daily_spread` endpoint in `main.py` to calculate the daily spread for both \"CDR.WA\" (CD Project Red) and \"11B.WA\" (11bits Studio) by calling the `calculate_daily_spread` function with the respective ticker as argument.\n",
      "5. The endpoint will then return the difference between the daily spreads of the two stocks.\n",
      "\n",
      "Please confirm if this plan is correct and I can proceed with the changes.\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  go with the plan\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "go with the plan\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_cqaVQJ6VQjR7lh114bxJGVfi): create_file_with_code *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"spread_calculation.py\",\n",
      "  \"code\": \"import yfinance as yf\\n\\ndef calculate_daily_spread(ticker):\\n    stock = yf.Ticker(ticker)\\n    today_data = stock.history(period=\\\"1d\\\")\\n    spread = ((today_data[\\\"High\\\"] - today_data[\\\"Low\\\"]) / today_data[\\\"Low\\\"]) * 100\\n    return spread\"\n",
      "}\n",
      "\u001b[32m**************************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION create_file_with_code...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_cqaVQJ6VQjR7lh114bxJGVfi\" *****\u001b[0m\n",
      "[0, \"File created successfully\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_qcoMK0RO5bXdY4yQz5RCh4mp): modify_code *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"main.py\",\n",
      "  \"start_line\": 1,\n",
      "  \"end_line\": 11,\n",
      "  \"new_code\": \"from fastapi import FastAPI\\nfrom spread_calculation import calculate_daily_spread\\n\\napp = FastAPI()\\n\\n@app.get(\\\"/cdr_daily_spread\\\")\\nasync def compare_daily_spread():\\n    cdr_spread = calculate_daily_spread(\\\"CDR.WA\\\")\\n    bits_spread = calculate_daily_spread(\\\"11B.WA\\\")\\n    return cdr_spread - bits_spread\"\n",
      "}\n",
      "\u001b[32m****************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  Do not change whole the file. concentrate on the concrete lines.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_qcoMK0RO5bXdY4yQz5RCh4mp\" *****\u001b[0m\n",
      "USER INTERRUPTED\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "Do not change whole the file. concentrate on the concrete lines.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_hz1v2vEPPxKHeygjqs2lc8ii): modify_code *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"main.py\",\n",
      "  \"start_line\": 1,\n",
      "  \"end_line\": 2,\n",
      "  \"new_code\": \"from fastapi import FastAPI\\nfrom spread_calculation import calculate_daily_spread\\nimport yfinance as yf\"\n",
      "}\n",
      "\u001b[32m****************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION modify_code...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_hz1v2vEPPxKHeygjqs2lc8ii\" *****\u001b[0m\n",
      "[0, \"Code modified\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_1ABNdk6AATaVvn8UqLKBD5ZR): modify_code *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"main.py\",\n",
      "  \"start_line\": 6,\n",
      "  \"end_line\": 11,\n",
      "  \"new_code\": \"@app.get(\\\"/cdr_daily_spread\\\")\\nasync def compare_daily_spread():\\n    cdr_spread = calculate_daily_spread(\\\"CDR.WA\\\")\\n    bits_spread = calculate_daily_spread(\\\"11B.WA\\\")\\n    return cdr_spread - bits_spread\"\n",
      "}\n",
      "\u001b[32m****************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  Check out file first to get actual lines position. Also, change endpoint name.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_1ABNdk6AATaVvn8UqLKBD5ZR\" *****\u001b[0m\n",
      "USER INTERRUPTED\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "Check out file first to get actual lines position. Also, change endpoint name.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_2vlnu0RJ11qg6ygGT6l2tS3Q): see_file *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"main.py\"\n",
      "}\n",
      "\u001b[32m*************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION see_file...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_2vlnu0RJ11qg6ygGT6l2tS3Q\" *****\u001b[0m\n",
      "[0, \"1:from fastapi import FastAPI\\n2:from spread_calculation import calculate_daily_spread\\n3:import yfinance as yf\\n4:\\n5:app = FastAPI()\\n6:\\n7:@app.get(\\\"/cdr_daily_spread\\\")\\n8:async def calculate_daily_spread():\\n9:    cdr = yf.Ticker(\\\"CDR.WA\\\")\\n10:    today_data = cdr.history(period=\\\"1d\\\")\\n11:    spread = ((today_data[\\\"High\\\"] - today_data[\\\"Low\\\"]) / today_data[\\\"Low\\\"]) * 100\\n12:    return spread\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_gNwVSM2u33Ej89Yc2IkSAovu): modify_code *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"main.py\",\n",
      "  \"start_line\": 7,\n",
      "  \"end_line\": 12,\n",
      "  \"new_code\": \"@app.get(\\\"/compare_daily_spread\\\")\\nasync def compare_daily_spread():\\n    cdr_spread = calculate_daily_spread(\\\"CDR.WA\\\")\\n    bits_spread = calculate_daily_spread(\\\"11B.WA\\\")\\n    return cdr_spread - bits_spread\"\n",
      "}\n",
      "\u001b[32m****************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION modify_code...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_gNwVSM2u33Ej89Yc2IkSAovu\" *****\u001b[0m\n",
      "[0, \"Code modified\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "The changes have been made successfully. Now, the FastAPI application has an endpoint `/compare_daily_spread` which calculates and returns the difference between the daily spreads of \"CDR.WA\" (CD Project Red) and \"11B.WA\" (11bits Studio). The calculation logic is now in a separate file `spread_calculation.py`.\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  Good. But add in return some addition description to be understandable which stock change is bigger. Remember to check out main.py first to actualize your knowledge.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "Good. But add in return some addition description to be understandable which stock change is bigger. Remember to check out main.py first to actualize your knowledge.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_1Clo7beP49gWm1oXQXK7W6RH): see_file *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"main.py\"\n",
      "}\n",
      "\u001b[32m*************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION see_file...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_1Clo7beP49gWm1oXQXK7W6RH\" *****\u001b[0m\n",
      "[0, \"1:from fastapi import FastAPI\\n2:from spread_calculation import calculate_daily_spread\\n3:import yfinance as yf\\n4:\\n5:app = FastAPI()\\n6:\\n7:@app.get(\\\"/compare_daily_spread\\\")\\n8:async def compare_daily_spread():\\n9:    cdr_spread = calculate_daily_spread(\\\"CDR.WA\\\")\\n10:    bits_spread = calculate_daily_spread(\\\"11B.WA\\\")\\n11:    return cdr_spread - bits_spread\\n\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_Cl6jBUwvfa8JGbyldfrzYfiB): modify_code *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"main.py\",\n",
      "  \"start_line\": 7,\n",
      "  \"end_line\": 11,\n",
      "  \"new_code\": \"@app.get(\\\"/compare_daily_spread\\\")\\nasync def compare_daily_spread():\\n    cdr_spread = calculate_daily_spread(\\\"CDR.WA\\\")\\n    bits_spread = calculate_daily_spread(\\\"11B.WA\\\")\\n    spread_difference = cdr_spread - bits_spread\\n    if spread_difference > 0:\\n        return {'message': 'CD Project Red has a larger daily spread', 'difference': spread_difference}\\n    elif spread_difference < 0:\\n        return {'message': '11bits Studio has a larger daily spread', 'difference': -spread_difference}\\n    else:\\n        return {'message': 'Both stocks have the same daily spread', 'difference': 0}\"\n",
      "}\n",
      "\u001b[32m****************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION modify_code...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_Cl6jBUwvfa8JGbyldfrzYfiB\" *****\u001b[0m\n",
      "[0, \"Code modified\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "The changes have been made successfully. Now, the `/compare_daily_spread` endpoint returns a dictionary with a message indicating which stock (CD Project Red or 11bits Studio) has a larger daily spread and the absolute difference between the daily spreads. If both stocks have the same daily spread, the message will indicate this and the difference will be 0.\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  ValueError: The truth value of a Series is ambiguous.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "ValueError: The truth value of a Series is ambiguous.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "The error message indicates that the comparison operation is being performed on a pandas Series object, which is ambiguous. This is likely because the `calculate_daily_spread` function is returning a Series object instead of a single value.\n",
      "\n",
      "To fix this, we need to ensure that the `calculate_daily_spread` function returns a single value. We can do this by taking the first (and only) value from the Series object. \n",
      "\n",
      "Here is the plan of changes:\n",
      "\n",
      "1. Modify the `calculate_daily_spread` function in `spread_calculation.py` to return only the first value from the `spread` Series.\n",
      "2. No changes are required in `main.py` as the returned value from `calculate_daily_spread` function will now be a single value.\n",
      "\n",
      "Please confirm if this plan is correct and I can proceed with the changes.\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  Cool. Remember to check out file before introducing modifications.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "Cool. Remember to check out file before introducing modifications.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_4wPhGFFW8pt8B28nVhVvWztN): see_file *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"spread_calculation.py\"\n",
      "}\n",
      "\u001b[32m*************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION see_file...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_4wPhGFFW8pt8B28nVhVvWztN\" *****\u001b[0m\n",
      "[0, \"1:import yfinance as yf\\n2:\\n3:def calculate_daily_spread(ticker):\\n4:    stock = yf.Ticker(ticker)\\n5:    today_data = stock.history(period=\\\"1d\\\")\\n6:    spread = ((today_data[\\\"High\\\"] - today_data[\\\"Low\\\"]) / today_data[\\\"Low\\\"]) * 100\\n7:    return spread\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_DL0p37GzppRSmoqFaOOLSNaI): modify_code *****\u001b[0m\n",
      "Arguments: \n",
      "\n",
      "{\n",
      "  \"filename\": \"spread_calculation.py\",\n",
      "  \"start_line\": 3,\n",
      "  \"end_line\": 7,\n",
      "  \"new_code\": \"def calculate_daily_spread(ticker):\\n    stock = yf.Ticker(ticker)\\n    today_data = stock.history(period=\\\"1d\\\")\\n    spread = ((today_data[\\\"High\\\"] - today_data[\\\"Low\\\"]) / today_data[\\\"Low\\\"]) * 100\\n    return spread.values[0]\"\n",
      "}\n",
      "\u001b[32m****************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION modify_code...\u001b[0m\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33mAdmin\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_DL0p37GzppRSmoqFaOOLSNaI\" *****\u001b[0m\n",
      "[0, \"Code modified\"]\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mEngineer\u001b[0m (to chat_manager):\n",
      "\n",
      "The changes have been made successfully. Now, the `calculate_daily_spread` function in `spread_calculation.py` returns a single value instead of a pandas Series. This should resolve the ValueError you were encountering.\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide feedback to chat_manager. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:  exit\n"
     ]
    }
   ],
   "source": [
    "chat_result = user_proxy.initiate_chat(\n",
    "    manager,\n",
    "    message=\"\"\"\n",
    "You will need to improve app in FastApi. For now, check out all the application files, try to understand it and wait for next instructions.\n",
    "\"\"\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41b6dc05-b1fc-4c1d-b101-4e91dfa63b43",
   "metadata": {},
   "source": [
    "## Result\n",
    "\n",
    "Finally, our agents modified a code so it looks like this:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0dec75d5-035d-4cd6-956e-cafb37f304e7",
   "metadata": {},
   "source": [
    "```python\n",
    "# backend_dir/main.py\n",
    "\n",
    "from fastapi import FastAPI\n",
    "from spread_calculation import calculate_daily_spread\n",
    "import yfinance as yf\n",
    "\n",
    "app = FastAPI()\n",
    "\n",
    "@app.get(\"/compare_daily_spread\")\n",
    "async def compare_daily_spread():\n",
    "    cdr_spread = calculate_daily_spread(\"CDR.WA\")\n",
    "    bits_spread = calculate_daily_spread(\"11B.WA\")\n",
    "    spread_difference = cdr_spread - bits_spread\n",
    "    if spread_difference > 0:\n",
    "        return {'message': 'CD Project Red has a larger daily spread', 'difference': spread_difference}\n",
    "    elif spread_difference < 0:\n",
    "        return {'message': '11bits Studio has a larger daily spread', 'difference': -spread_difference}\n",
    "    else:\n",
    "        return {'message': 'Both stocks have the same daily spread', 'difference': 0}\n",
    "\n",
    "\n",
    "# backend_dir/spread_calculation.py\n",
    "\n",
    "import yfinance as yf\n",
    "\n",
    "def calculate_daily_spread(ticker):\n",
    "    stock = yf.Ticker(ticker)\n",
    "    today_data = stock.history(period=\"1d\")\n",
    "    spread = ((today_data[\"High\"] - today_data[\"Low\"]) / today_data[\"Low\"]) * 100\n",
    "    return spread.values[0]\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4c1dc47-53b7-417f-af8b-f8c4d73c1d7c",
   "metadata": {},
   "source": [
    "You can check out work of application with Postman or curl and see the next output:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d52418e-9a67-4ea2-984e-5a14bdd78255",
   "metadata": {},
   "source": [
    "```json\n",
    "{\n",
    "    \"message\": \"11bits Studio has a larger daily spread\",\n",
    "    \"difference\": 1.7968083865943187\n",
    "}\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "front_matter": {
   "description": "Equip your agent with functions that can efficiently implement features into your software application.",
   "tags": [
    "function call",
    "code generation",
    "tool use",
    "software engineering"
   ]
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
